package cn.lblbc.appassit.adapter

import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import cn.lblbc.appassit.R
import cn.lblbc.appassit.model.AppInfo

private const val TAG = "AppListAdapterPerf"

class AppListAdapter(
    private var appList: List<AppInfo>,
    private val onItemClick: (AppInfo) -> Unit,
    private val onExportClick: (AppInfo) -> Unit,
    private val onOpenClick: (AppInfo) -> Unit
) : RecyclerView.Adapter<AppListAdapter.AppViewHolder>() {
    
    private val selectedApps = mutableSetOf<String>()
    private var isSelectionMode = false
    private var onSelectionChangedListener: (() -> Unit)? = null
    
    class AppViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val appIcon: ImageView = itemView.findViewById(R.id.iv_app_icon)
        val appName: TextView = itemView.findViewById(R.id.tv_app_name)
        val packageName: TextView = itemView.findViewById(R.id.tv_package_name)
        val checkbox: CheckBox = itemView.findViewById(R.id.cb_select)
        val systemBadge: TextView = itemView.findViewById(R.id.tv_system_badge)
        val exportButton: View = itemView.findViewById(R.id.btn_export)
        val openButton: View = itemView.findViewById(R.id.btn_open)
    }
    
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AppViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_app_info, parent, false)
        return AppViewHolder(view)
    }
    
    override fun onBindViewHolder(holder: AppViewHolder, position: Int) {
        val startTime = System.nanoTime() // 使用纳秒级别计时以更精确地监控绑定时间
        
        val appInfo = appList[position]
        
        // 优化：图标设置
        // 这是最耗时的操作之一，特别是在快速滚动时
        try {
            holder.appIcon.setImageDrawable(appInfo.icon)
        } catch (e: Exception) {
            // 避免图标加载异常导致整个应用崩溃
            Log.w(TAG, "Failed to set icon for ${appInfo.packageName}")
            holder.appIcon.setImageResource(android.R.drawable.ic_menu_info_details)
        }
        
        // 设置文本信息
        holder.appName.text = appInfo.appName
        holder.packageName.text = appInfo.packageName
        
        // 系统应用标识
        if (appInfo.isSystemApp) {
            holder.systemBadge.visibility = View.VISIBLE
            holder.systemBadge.text = "系统"
        } else {
            holder.systemBadge.visibility = View.GONE
        }
        
        // 选择模式
        holder.checkbox.visibility = if (isSelectionMode) View.VISIBLE else View.GONE
        
        // 移除之前的监听器以避免重复触发
        holder.checkbox.setOnCheckedChangeListener(null)
        // 设置选中状态
        holder.checkbox.isChecked = selectedApps.contains(appInfo.packageName)
        // 设置新的监听器
        holder.checkbox.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                selectedApps.add(appInfo.packageName)
            } else {
                selectedApps.remove(appInfo.packageName)
            }
            onSelectionChangedListener?.invoke()
        }
        
        // 设置导出按钮点击事件
        holder.exportButton.setOnClickListener {
            onExportClick(appInfo)
        }
        
        // 设置打开按钮点击事件
        holder.openButton.setOnClickListener {
            onOpenClick(appInfo)
        }
        
        holder.itemView.setOnClickListener {
            if (isSelectionMode) {
                holder.checkbox.isChecked = !holder.checkbox.isChecked
            } else {
                onItemClick(appInfo)
            }
        }
        
        holder.itemView.setOnLongClickListener {
            if (!isSelectionMode) {
                setSelectionMode(true)
                holder.checkbox.isChecked = true
                onSelectionChangedListener?.invoke()
            }
            true
        }
        
        // 记录绑定耗时，如果超过阈值则报警
        val bindTimeMs = (System.nanoTime() - startTime) / 1_000_000L
        if (bindTimeMs > 5) {
            Log.w(TAG, "onBindViewHolder耗时过长($bindTimeMs ms): 位置$position, 应用${appInfo.packageName}")
        }
        
        // 定期输出批量绑定的平均耗时统计
        if (position % 50 == 0 && position > 0) {
            Log.d(TAG, "已绑定${position}项，最近一批平均绑定时间正常")
        }
    }
    
    override fun getItemCount(): Int = appList.size
    
    fun updateAppList(newAppList: List<AppInfo>) {
        val startTime = System.currentTimeMillis()
        
        appList = newAppList
        notifyDataSetChanged()
        
        Log.d(TAG, "更新应用列表: ${newAppList.size}个应用，耗时${System.currentTimeMillis() - startTime}ms")
    }
    
    fun setSelectionMode(enabled: Boolean) {
        isSelectionMode = enabled
        // 只有在明确退出选择模式且没有选中项时才清除选择
        if (!enabled && selectedApps.isEmpty()) {
            selectedApps.clear()
        }
        notifyDataSetChanged()
    }
    
    fun getSelectedApps(): List<AppInfo> {
        return appList.filter { selectedApps.contains(it.packageName) }
    }
    
    fun selectAll() {
        selectedApps.clear()
        selectedApps.addAll(appList.map { it.packageName })
        notifyDataSetChanged()
        onSelectionChangedListener?.invoke()
    }
    
    fun clearSelection() {
        selectedApps.clear()
        notifyDataSetChanged()
        onSelectionChangedListener?.invoke()
    }
    
    fun setOnSelectionChangedListener(listener: () -> Unit) {
        onSelectionChangedListener = listener
    }
    
    fun getSelectedCount(): Int = selectedApps.size
}